public class LeetCode443 {
    public static void main(String[] args) {
        LeetCode443 leetCode443 = new LeetCode443();
        System.out.println(leetCode443.compress("aabbbbbbbbbbcc".toCharArray()));
    }

    public int compress(char[] chars) {
        int resultIndex = 0;
        if (chars.length <= 0){
            return resultIndex;
        }
        char currentChar = chars[0];
        int currentCharLength = 0;
        for (int i = 0; i < chars.length; i++){
            if(chars[i] == currentChar){
                currentCharLength++;
                if(i == chars.length - 1){
                    resultIndex = saveCharAndLength(currentChar, currentCharLength, resultIndex, chars);
                }
                continue;
            }

            resultIndex = saveCharAndLength(currentChar, currentCharLength, resultIndex, chars);
            currentChar = chars[i];
            currentCharLength = 1;
            if(i == chars.length - 1){
                resultIndex = saveCharAndLength(currentChar, currentCharLength, resultIndex, chars);
            }
        }
        return resultIndex;
    }

    public int saveCharAndLength(char currentChar, int currentCharLength, int resultIndex, char[] chars){
        chars[resultIndex++] = currentChar;
        if(currentCharLength > 1) {
            for (char c : String.valueOf(currentCharLength).toCharArray()) {
                chars[resultIndex++] = c;
            }
        }
        return resultIndex;
    }

    //这个算法只输出了长度
    public int compress1(char[] chars) {
        int result = 0;
        if (chars.length <= 0){
            return result;
        }

        char currentChar = chars[0];
        int currentCharLength = 0;
        for(char c : chars){
            if(c == currentChar){
                currentCharLength++;
            }else {
                result++;
                if(currentCharLength != 1){
                    int lengthCharSize = String.valueOf(currentCharLength).length();
                    result += lengthCharSize;
                }
                currentChar = c;
                currentCharLength = 1;
            }
        }

        result++;
        if(currentCharLength != 1){
            int lengthCharSize = String.valueOf(currentCharLength).length();
            result += lengthCharSize;
        }
        return result;
    }
}
